package com.bigknow.appstore.proxy.handler.register;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.handler.base.BaseOutboundHandler;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.vo.RequestVo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpMessage;

import java.util.Date;

/**
 * 在返回信息中加入setCookie
 * Created by chaos on 2016/10/24.
 */
public class SetUserCookieHandler extends BaseOutboundHandler {

    public SetUserCookieHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer) {
        super(proxyServer, cacheManager, writer);
    }

    @Override
    public void write(ChannelHandlerContext ctx, FullHttpMessage msg, ChannelPromise promise) {

        if (getRequestVo(ctx) != null) {
            RequestVo requestVo = getRequestVo(ctx);
            if (requestVo.getUserId() != null) {
                msg.headers().add("Set-Cookie",
                        String.format("userId=%s; expires=%s; path=/", requestVo.getUserId(), new Date().toString()));
            }
        }
        ctx.write(msg, promise);
    }
}
